package app.controllers;

import app.Const;
import app.models.sys.User;
import com.google.common.base.Strings;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.Restful;
import goja.Logger;
import goja.mvc.Controller;
import goja.mvc.kit.Requests;
import goja.security.shiro.AppUser;
import goja.security.shiro.LoginActionKit;
import goja.security.shiro.Securitys;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.joda.time.DateTime;

import static app.Const.MESSAGE_ATTR;

/**
 * <p> 用户登录请求 </p>
 *
 * @author sogYF
 * @version 1.0
 * @since JDK 1.6
 */
@Before(Restful.class)
public class LoginController extends Controller {



    public void index() {
        if (Securitys.isLogin()) {
            redirect("/dashborad");
        } else {
            int error = getParaToInt("error", 0);
            if (error > 0) {
                switch (error) {
                    case 1:
                        setAttr(MESSAGE_ATTR, "用户名或者密码错误");
                        break;
                    case 2:
                        setAttr(MESSAGE_ATTR, "账号已经被锁定无法登录！");
                        break;
                    case 3:
                        setAttr(MESSAGE_ATTR, "请输入用户名和登录密码！");
                        break;
                }
            }
            String username = getPara(Const.FIELD_NAME);
            setAttr("username", username);
            render("/login.ftl");
        }
    }

    public void save() {
        String password = getPara(FormAuthenticationFilter.DEFAULT_PASSWORD_PARAM);
        String username = getPara(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
        if (Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(password)) {
            redirect("/login?error=3&name=" + username);
            return;
        }
        try {

            LoginActionKit.login(username, password, false);
        } catch (DisabledAccountException e) {
            Logger.error("用户禁用！", e);
            redirect("/login?error=2&name=" + username);
            return;
        } catch (AuthenticationException e) {
            Logger.error("用户名或者密码错误！", e);
            redirect("/login?error=1&name=" + username);
            return;
        }

        final AppUser<User> loginUser = Securitys.getLogin();
        loginUser.getUser().set("last_login_ip", Requests.remoteAddr(getRequest()))
                .set("last_login_time", DateTime.now()).update();

        final String rediectLoginUrl = "/about";
        if (Strings.isNullOrEmpty(rediectLoginUrl)) {
            redirect("/login?error=1&name=" + username);
        } else {
            redirect(rediectLoginUrl);
        }
    }
}
